<?php


namespace App\Commons\Domain\Module\Exchange\Entity;

use App\Commons\Domain\Core\DomainEntity;
use App\Commons\Domain\Module\Exchange\Model\Order;
use App\Commons\Domain\Module\Financial\Model\Wallet;

class OrderEntity extends DomainEntity
{
    public const ENTITY = Order::class;


    /**
     * 创建订单
     * @param array $data
     * @return mixed
     */
    public function createOrder(array $data)
    {
        return $this->create($data);
    }

    /**
     * 买方付款
     * @param string $order_no
     * @param int $payment_id
     * @return mixed
     */
    public function payOrder(string $order_no, int $payment_id)
    {
        // 获取对应的订单
        $order = $this->whereOrderNo($order_no)->firstOrFail();
        $order->payment_id = $payment_id;
        $order->pay_at = now();

        return $order->save();
    }

    /**
     * 卖方放币
     * @param string $uid
     * @param string $order_no
     * @return mixed
     */
    public function confirmOrder(string $uid, string $order_no)
    {
        return db_trans(function () use ($uid, $order_no) {
            $order = $this->whereOrderNo($order_no)->firstOrFail();
            $order->put_at = now();
            $order->status = 2;

            return tap($order)->save();
        });
    }

    /**
     * 取消订单
     * @param string $order_no
     * @return mixed
     */
    public function cancelOrder(string $order_no)
    {
        return tap($this->whereOrderNo($order_no)->firstOrFail())->update(['status' => 3]);
    }
}
